import socket, threading
import time
from My_signal import Communicator


class My_socket:
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port
        self.client_list = []
        self.communicator = Communicator()

    def start_tcp(self):
        print("开启TCP")
        try:
            with socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) as self.server:
                self.server.bind((self.ip, self.port))
                self.server.listen()
                print("tcp server start...")

                while True:
                    if not self.server:
                        break
                    client_socket, client_addr = self.server.accept()
                    print(f"新的连接进入{client_addr}")
                    # 绑定信号与槽
                    self.communicator.custom_signal.connect(self.send_data)
                    t = threading.Thread(target=self.recv_data, args=(client_socket, client_addr))
                    self.client_list.append(client_socket)
                    t.start()
        except Exception as e:
            print("error:", e)

    def recv_data(self, client_socket: socket.socket, client_addr):
        try:
            while True:
                data = client_socket.recv(1024)
                if not data:
                    break
                print(f"接收到{client_addr}的消息:{data.decode('gbk')}")
        except ConnectionAbortedError:
            print(f"连接被{client_addr}中断")
        except Exception as e:
            print(f"与{client_addr}连接时发生错误", e)
        finally:
            self.client_list.remove(client_socket)
            client_socket.close()

    def send_data(self, msg):
        print(f"要发送的消息:{msg}")
        pass

    def close_tcp(self):
        self.server.close()
        self.server = None
        if len(self.client_list):
            for client in self.client_list:
                client.close()

